<template>
  <div>
    <!-- 结单待支付页面 -->
    <el-dialog
      v-el-drag-dialog
      title="结单待支付"
      :visible.sync="visible"
      width="1024px"
      append-to-body
      @close="reset"
    >
      <el-form ref="form" class="form" :model="temp" label-width="120px" label-position="right">
        <el-form-item label="订单号:">
          <el-input
            v-model="temp.orderCode"
            disabled
          />
        </el-form-item>
        <el-form-item label="应支付金额:">
          <el-input
            v-model="decimalSpare4"
            disabled
          />
        </el-form-item>

        <!-- 支付方式 -->
        <el-form-item label="请选择支付方式:" style="width: 100%;">
          <br>
          <el-tabs v-model="activeName" @tab-click="handleClick">
            <el-tab-pane label="现金" name="first">请收取现金</el-tab-pane>
            <!-- <el-tab-pane v-if="isPay.showLinePay === 'true'" label="微信" name="tencent">
              <div v-show="false" :key="base64Text" ref="qrCodeUrl" />
              <img v-if="activeName === 'tencent' && mode==='qrcode'" :src="base64Text" alt="">
              <img v-if="activeName === 'tencent' && mode==='box'" src="../../../../assets/pay-wechat.gif" alt="">
            </el-tab-pane>
            <el-tab-pane v-if="isPay.showLinePay === 'true'" label="支付宝" name="alibaba">
              <div v-show="false" :key="base64Text" ref="qrCodeUrl" />
              <img v-if="activeName === 'alibaba' && mode==='qrcode'" :src="base64Text" alt="">
              <img v-if="activeName === 'alibaba' && mode==='box'" src="../../../../assets/pay-zfb.gif" alt="">
            </el-tab-pane> -->
            <el-tab-pane v-if="isPay.showCsmCard === 'true'" label="预付卡" name="prepayCrad">
              <el-form class="precard-form" inline label-width="80px" label-position="right">
                <div v-for="(item,index) in temp.csmCardList" :key="index">
                  <el-form-item v-show="item.cardCode" label="卡号:">
                    <el-input v-model="item.cardCode" disabled />
                  </el-form-item>
                  <el-form-item v-show="item.cardCode" label="主副卡:">
                    <el-select v-model="item.isMainCard" disabled placeholder="请选择">
                      <el-option
                        v-for="childItem in [{desc:'主卡',value:1},{desc:'副卡',value:2}]"
                        :key="childItem.value"
                        :label="childItem.desc"
                        :value="childItem.value"
                      />
                    </el-select>
                  </el-form-item>
                  <el-form-item v-show="item.cardSurplus" label="卡内余额:" prop="cardSurplus">
                    <el-input :value="(item.cardSurplus/ 100).toFixed(2)" disabled />
                  </el-form-item>
                </div>
                <el-form-item v-if="temp.csmCardList&&temp.csmCardList.length===2" label="总余额:" prop="cardSurplus">
                  <el-input :value="((temp.csmCardList[0].cardSurplus+temp.csmCardList[1].cardSurplus)/ 100).toFixed(2)" disabled />
                </el-form-item>
                <el-form-item v-if="temp.csmCardList&&temp.csmCardList.length===1" label="总余额:" prop="cardSurplus">
                  <el-input :value="(temp.csmCardList[0].cardSurplus/ 100).toFixed(2)" disabled />
                </el-form-item>
                <el-form-item v-show="checkWay === 1" label="预付卡密码:" prop="passWord" label-width="100px">
                  <el-input v-model.trim="temp.passWord" type="password" :minlength="6" :maxlength="6" autocomplete="off" />
                </el-form-item>
                <el-form-item v-show="checkWay === 2" label="手机号:" prop="csmPhone">
                  <el-input v-model.trim="temp.csmPhone" placeholder="请输入手机号">
                    <el-button slot="append" class="append-search" :disabled="btn_disabled" @click="sendMessageCode">{{ btn_text }}</el-button>
                  </el-input>
                </el-form-item>
                <el-form-item v-show="checkWay === 2" class="yzm-form-item" prop="messageCode" label="验证码:">
                  <el-input v-model.trim="temp.messageCode" placeholder="请输入验证码" :minlength="6" :maxlength="6" autocomplete="off" />
                </el-form-item>
              </el-form>
            </el-tab-pane>
            <el-tab-pane v-if="isPay.showMonthPay === 'true'" label="月结" name="monthKnot">
              月结({{ isPay.settlementUseMonery }} / {{ isPay.decimalSpare2 }})
            </el-tab-pane>
            <el-tab-pane v-if="isPay.showICBC ==='true'" label="银行支付" name="commerce">
              <div v-show="false" :key="base64Text" ref="qrCodeUrl" />
              <img v-if="activeName === 'commerce'" :src="base64Text" alt="">
            </el-tab-pane>
          </el-tabs>
          <div v-if="activeName === 'tencent' || activeName === 'alibaba'" class="mode-btn">
            <el-button v-if="mode==='qrcode'" type="primary" @click="modeChange('box')">切换刷卡模式</el-button>
            <el-button v-else type="primary" @click="modeChange('qrcode')">切换扫码模式</el-button>
          </div>
          <el-input ref="inputCardCodeDom" v-model="inputCardCode" v-focus class="hide" @keyup.enter.native="getCardCode" />
        </el-form-item>
      </el-form>
      <div v-if="activeName === 'first' || activeName === 'monthKnot' || activeName === 'prepayCrad'" slot="footer" class="dialog-footer">
        <el-button @click="visible = false">
          关闭
        </el-button>
        <el-button type="primary" @click="save">提交</el-button>
        <el-button v-if="activeName === 'prepayCrad' && info.accCsmCardConfigInfo.checkWay === 4" plain @click="changeCheckWay">{{ checkWay === 1 ? '切换手机验证码校验' : '切换密码校验' }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    saveLorryOrderParam,
    saveLorryOrderGetICBCCode,
    saveLorryOrderObtainAuthorize,
    saveLorryOrderObtainSave,
    queryWsaleOrderBillPayStatus,
    getWsalePayPhoneCode,
    queryCsmCardCodeByOrderCode,
    sendMessage,
    savePayWsalesOrderCodeByCard
  } from '@/api'
  import QRCode from 'qrcodejs2'
  import { accDiv } from '@/utils/math'
  import { isWildPhone,
           toDecimal
  } from '@/utils'

  export default {
    name: 'to-ay',
    directives: {
      focus: {
        inserted: function(el) {
          el.querySelector('input').focus()
        }
      }
    },
    data() {
      return {
        visible: false,
        checkWay: 0, // 0表示无校验 1表示密码校验 2表示验证码校验
        countdown: 60, // 发送验证码时间60秒
        startSendMessageCode: 0, // 发送验证码时间初始化为0
        btn_disabled: false, // 获取验证码按钮是否禁用
        btn_text: '获取验证码', // 获取验证码按钮的文字
        timer: null,
        isPayStatus: false, // false初始值表示支付未成功,true表示支付成功
        base64Text: '',
        mode: 'qrcode', // 付款模式，qrcode扫码，box扫码盒子
        isPay: {},
        checkInterval: '',
        timeEndOut: 0,
        paymentMethod: '',
        temp: {
          decimalSpare4: 0,
          cardCode: '',
          cardSurplus: '',
          passWord: '',
          messageCode: '',
          csmPhone: ''
        },
        info: {
          accCsmCardConfigInfo: {
            checkWay: ''
          }
        },
        QRImg: {},
        activeName: 'first',
        transactionId: '', // 微信支付成功返回编号
        inputCardCode: '' // 扫码盒子扫码完成后返回的字符串
      }
    },
    computed: {
      decimalSpare4: function() {
        return this.temp.decimalSpare4.toFixed(2)
      },
      cardSurplus: function() {
        return this.info.cardSurplus ? accDiv(Number(this.info.cardSurplus), 100).toFixed(2) : ''
      }
    },
    methods: {
      async open(temp, money) {
        this.temp = temp
        this.temp.decimalSpare4 = money ? Number(money) : 0
        // this.gainQRCode()
        const res = await saveLorryOrderParam({
          orderCode: temp.orderCode,
          tReceivables: this.temp.decimalSpare4.toFixed(2)
        })
        this.isPay = res.data
        if (this.isPay.showCsmCard === 'true') {
          this.activeName = 'prepayCrad'
          this.selectCsmCardCodeByOrderCode()
        } else if (this.isPay.showMonthPay === 'true') {
          this.activeName = 'monthKnot'
        }
        this.handleClick(this.activeName)
        return new Promise(resolve => {
          this.resolve = resolve
          this.visible = true
        })
      },
      handleClick(tab, event) {
        this.closeChecking()
        if (tab.name === 'tencent' || tab.name === 'alibaba' || tab.name === 'commerce') {
          this.gainQRCode()
        } else if (tab.name === 'prepayCrad') {
          this.paymentMethod = '256'
          this.selectCsmCardCodeByOrderCode()
        } else if (tab.name === 'monthKnot') {
          this.monthKnotCanUse()
        }
      },
      monthKnotCanUse() {
        if (toDecimal(this.isPay.decimalSpare2, 2) - toDecimal(this.isPay.settlementUseMonery, 2) < toDecimal(this.isPay.orderMoney, 2)) {
          this.$message.error('月结额度不够,请选用其他方式付款')
          return false
        } else {
          return true
        }
      },
      // 根据批发订单查询客户预付卡
      async selectCsmCardCodeByOrderCode() {
        const res = await queryCsmCardCodeByOrderCode({
          orderCode: this.temp.orderCode,
          billType: 128, // 取Ord_BillType中预付卡值
          payMoney: this.temp.decimalSpare4
        })
        this.info = res.data
        this.temp = Object.assign(this.temp, res.data)
        if (res.data.accCsmCardConfigInfo.checkWay === 1) this.checkWay = 0
        else if (res.data.accCsmCardConfigInfo.checkWay === 2 || res.data.accCsmCardConfigInfo.checkWay === 4) this.checkWay = 1
        else if (res.data.accCsmCardConfigInfo.checkWay === 3) this.checkWay = 2
      },
      // 客户押金单支付获取微信/支付宝授权生成二维码
      async gainQRCode() {
        var res = {}
        if (this.activeName === 'commerce') {
          res = await saveLorryOrderGetICBCCode({
            orderCode: this.temp.orderCode,
            payMoney: this.temp.decimalSpare4
          })
          this.QRImg = res.data
          const casService = `${this.QRImg.codeUrl}`
          const codeUrl = casService
          this.creatQrCode(codeUrl)
        } else {
          if (this.activeName === 'tencent' || this.activeName === 'alibaba') {
            res = await saveLorryOrderObtainAuthorize({
              orderCode: this.temp.orderCode,
              payMoney: this.temp.decimalSpare4 * 100,
              payWay: this.activeName
            })
          }
        }
        this.QRImg = res.data
        // const uuid = this.QRImg.prePayId
        const casService = `${this.QRImg.codeUrl}`
        const codeUrl = casService
        this.creatQrCode(codeUrl)
        // 轮询开启
        this.timeEndOut = 1000
        this.checkingPay()
      },
      creatQrCode(url) {
        // 解决qrcode动态生成二维码时多次点击生成多个二维码的问题
        // document.getElementById('qrcode').innerHTML = ''
        const code = new QRCode(this.$refs.qrCodeUrl, {
          text: url,
          width: 300,
          height: 300,
          colorDark: '#000000',
          colorLight: '#ffffff',
          correctLevel: QRCode.CorrectLevel.Q
        })
        const canvas = code._el.querySelector('canvas')// 获取生成二维码中的canvas，并将canvas转换成base64
        this.base64Text = canvas.toDataURL('image/png')
      },
      // 提交
      async save() {
        if (this.activeName === 'first') {
          this.paymentMethod = '1'
        }
        if (this.activeName === 'monthKnot') {
          this.paymentMethod = '16'
          const f = this.monthKnotCanUse()
          if (!f) return
        }
        if (this.activeName === 'prepayCrad') {
          this.paymentMethod = '256'
          console.log(this.temp.cardCode)
          // 校验预支付卡号和余额
          if (!this.temp.cardCode) {
            await this.selectCsmCardCodeByOrderCode()
            if (!this.cardSurplus) {
              return
            }
          }
          // 交易密码
          if (this.checkWay === 1) {
            if (!this.temp.passWord) {
              this.$message.error('请输入预付卡密码')
              return
            }

            if (this.temp.passWord.length !== 6) {
              this.$message.error('预付卡密码不对')
              return
            }
          }
          // 校验验证码
          if (this.checkWay === 2) {
            if (!this.temp.messageCode) {
              this.$message.error('请输入验证码')
              return
            }

            if (this.temp.messageCode.length !== 6) {
              this.$message.error('验证码密码不对')
              return
            }
          }
          this.$confirm('确认预付卡支付', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(async() => {
            this.precardSubmit()
          })
          return
        }
        this.$confirm(`${this.activeName === 'first' ? '确认现金支付?' : this.activeName === 'monthKnot' ? '确认月结支付?' : '确认预付卡支付?'}`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async() => {
          const { status } = await saveLorryOrderObtainSave({
            orderCode: this.temp.orderCode,
            tReceivables: this.temp.decimalSpare4.toFixed(2),
            paymentMethod: this.paymentMethod
          })
          if (status === 200) {
            this.$message({
              type: 'success',
              message: `${this.activeName === 'first' ? '现金支付成功！' : '月结支付成功！'}`
            })
            this.$parent.$parent.$parent.search()
            this.visible = false
          }
        })
      },
      async precardSubmit() {
        const res = await savePayWsalesOrderCodeByCard({
          orderCode: this.temp.orderCode,
          tReceivables: this.temp.decimalSpare4.toFixed(2),
          paymentMethod: this.paymentMethod,
          cardCode: this.temp.cardCode,
          passWord: this.temp.passWord,
          messageCode: this.temp.messageCode
        })
        if (res.status === 200) {
          this.$message({
            type: 'success',
            message: '预付卡支付成功'
          })
          this.$parent.$parent.$parent.search()
          this.visible = false
        }
      },
      // 定时器
      checkingPay() {
        const _this = this
        _this.checkInterval = setInterval(function() {
          if (_this.timeEndOut === 0) {
            clearInterval(_this.checkInterval)
          }
          if (_this.timeEndOut > 0) {
            var timeEndOut = _this.timeEndOut
            timeEndOut--
            _this.timeEndOut = timeEndOut
            _this.selectPayStatus()
          }
        }, 1000)
      },
      // 支付轮询查看押金订单是否支付成功
      async selectPayStatus() {
        if (this.isPayStatus) { // 说明支付成功
          return
        }
        const res = await queryWsaleOrderBillPayStatus({ orderCode: this.temp.orderCode })
        if (res.data.payStatus === 3) { // 表示已支付
          this.isPayStatus = true
          this.closeChecking()
          // 支付成功,表示结单成功,修改库存信息
          this.signOrder()
        }

        // 微信扫手机操作
        if (this.transactionId !== '') { // 说明微信扫手机支付成功
          this.isPayStatus = true
          this.closeChecking()
          // 支付成功,表示结单成功,修改库存信息
          this.signOrder()
        }
      },
      async signOrder() {
        const res = await saveLorryOrderObtainSave({
          orderCode: this.temp.orderCode
        })
        if (!this.isPayStatus) {
          return
        }
        if (res.exc != null) {
          this.$message.error(res.exc)
          return
        }
        this.isPayStatus = false
        if (this.transactionId !== '') {
          this.$message.success('支付成功,本次交易号是:' + this.transactionId, 5000)
          this.visible = false
          this.resolve()
        } else {
          this.$message.success('支付成功')
          this.visible = false
          this.resolve()
          this.$parent.$parent.$parent.search()
        }
        this.closeChecking()
      },
      async modeChange(mode) {
        this.mode = mode
        if (mode === 'box') { // 扫码盒子模式
          this.$refs.inputCardCodeDom.focus()
        }
      },
      async getCardCode() {
        if (!this.inputCardCode) return
        const res = await getWsalePayPhoneCode({
          paymentMethod: this.activeName === 'tencent' ? 2 : 128,
          payCardCode: this.inputCardCode,
          orderCode: this.temp.orderCode
        })
        if (!res.data) {
          this.$message.warning('没有查询到相关数据')
          return
        }
        // 说明支付成功
        if (res.data.scanCode !== this.inputCardCode) {
          this.$message.warning('刷卡支付失败')
        } else {
          this.transactionId = res.data.transactionId
        }
      },
      closeChecking() {
        if (this.checkInterval != null) {
          clearInterval(this.checkInterval)
          this.checkInterval = null
        }
      },
      // 发送验证码60秒倒计时
      async sendMessageCode() {
        if (!this.temp.csmPhone || !isWildPhone(this.temp.csmPhone)) {
          this.$message.warning('请输入正确的电话号码!')
          return
        }
        if (this.startSendMessageCode === 0) {
          this.startSendMessageCode === 1
          await sendMessage({
            csmPhone: this.temp.csmPhone,
            type: 1
          })
          this.settime()
        }
      },
      settime() {
        const _this = this
        if (this.countdown === 0) {
          this.$set(this, 'btn_disabled', false)
          this.$set(this, 'btn_text', '获取验证码')
          this.countdown = 60
          this.startSendMessageCode === 0
          return
        } else {
          this.$set(this, 'btn_disabled', true)
          this.$set(this, 'btn_text', `重新发送(${this.countdown})`)
          this.countdown--
        }
        this.timer = setTimeout(function() {
          _this.settime()
        }, 1000)
      },
      // 切换校验方式
      changeCheckWay() {
        if (this.checkWay === 1) this.checkWay = 2
        else this.checkWay = 1
      },
      reset() {
        this.qrcode = 'qrcode'
        this.QRImg = {}
        this.isPayStatus = false
        this.activeName = 'first'
        this.transactionId = ''
        this.inputCardCode = ''
        this.isPay = {}
        this.checkWay = 0 // 0表示无校验 1表示密码校验 2表示验证码校验
        this.countdown = 60 // 发送验证码时间60秒
        this.startSendMessageCode = 0 // 发送验证码时间初始化为0
        this.btn_disabled = false // 获取验证码按钮是否禁用
        this.btn_text = '获取验证码' // 获取验证码按钮的文字
        this.timer = null
        this.isPayStatus = false // false初始值表示支付未成功,true表示支付成功
        this.base64Text = ''
        this.mode = 'qrcode'
        this.info = {
          accCsmCardConfigInfo: {
            checkWay: ''
          }
        }
        this.temp = {
          decimalSpare4: 0,
          cardCode: '',
          cardSurplus: '',
          passWord: '',
          messageCode: '',
          csmPhone: ''
        }
        this.checkInterval = ''
        this.timeEndOut = 0
        this.closeChecking()
      }
    }
  }
</script>

<style lang="scss" scoped>
.form {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  & /deep/ .el-form-item {
    width: 50%;
  }
  .block {
    width: 100%;
  }
  .el-tab-pane {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
  }
  .hide {
    width: 0;
    height: 0;
    /deep/ .el-input__inner {
      width: 0;
      height: 0;
      border: none;
    }
  }
  .precard-form {
    & /deep/ .el-form-item {
      width: 45%;
    }
  }
  .mode-btn {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    margin-top: 10px;
  }
}
</style>
